<template>
  <div class="app-container">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="130px">
      <el-form-item label="读卡类型:">
        <el-radio-group v-model="form.medicalReadCardType">
          <el-radio v-for="dict in dictDataMap['medical_read_card_type']" :key="dict.dictValue"
                    :value="dict.dictValue">{{
              dict.dictLabel
            }}
          </el-radio>
        </el-radio-group>
        <el-button class="ml20" type="primary" @click="handleReadCard('01103')">
          <svg-icon class="mr5" icon-class="readCard"/>
          读卡
        </el-button>
        <el-button type="success" @click="submitForm">入院登记</el-button>
        <el-button type="warning" v-if="isMedical" @click="mdtrt">医保登记</el-button>
        <el-button type="primary" v-if="isMedical" @click="mdtrtUpdate">医保信息变更</el-button>
        <el-button type="danger" v-if="isMedical" @click="mdtrtCancel">医保登记撤销</el-button>
      </el-form-item>

      <el-divider content-position="left"><span class="divider-title">▶基本信息◀</span></el-divider>
      <el-row class="extra-margin">
        <el-col :span="6">
          <el-form-item label="患者姓名" prop="name">
                        <span v-if="form.name">
                            <span class="ys-css">{{ form.name }}</span>
                            <span v-if="form.newbornFlag === 'Y'">(新生儿)</span>
                        </span>
            <el-link v-else type="primary" @click="drawerClick">请点击选择需要登记的患者</el-link>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="性别" prop="sex">
            <el-select v-model="form.sex" placeholder="请选择性别">
              <el-option v-for="dict in dictDataMap['sys_user_sex']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-row>
            <el-col :span="8" style="margin-right: -40px;">
              <el-form-item label="年龄" prop="age">
                <el-input v-model="form.age" placeholder="岁" class="age" ref="ageRef">
                  <template #append>岁</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" style="margin-right: -40px;">
              <el-form-item prop="ageMonth">
                <el-input v-model="form.ageMonth" placeholder="月" class="age">
                  <template #append>月</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" style="margin-right: -40px;">
              <el-form-item prop="ageDay">
                <el-input v-model="form.ageDay" placeholder="天" class="age">
                  <template #append>天</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="身份证号" prop="idNo">
            <el-input v-model="form.idNo" placeholder="请输入身份证号" @blur="certificateNoBlur"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="民族" prop="nation">
            <el-select v-model="form.nation" placeholder="请选择民族">
              <el-option v-for="dict in dictDataMap['nation_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="国籍" prop="nationality">
            <el-select v-model="form.nationality" placeholder="请选择国籍">
              <el-option v-for="dict in dictDataMap['nationality_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5" v-if="form.newbornFlag === 'Y'">
          <el-row>
            <el-col :span="12" style="margin-right: -40px;">
              <el-form-item label="出生时刻" prop="ageHours">
                <el-input v-model="form.ageHours" class="age"  placeholder="时">
                  <template #append>时</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="margin-right: -40px;">
              <el-form-item prop="ageMinutes">
                <el-input v-model="form.ageMinutes" class="age"  placeholder="分">
                  <template #append>分</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入电话"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生日" prop="birthdayDate">
            <el-date-picker v-model="form.birthdayDate"  type="date" value-format="YYYY-MM-DD"
                            placeholder="请选择生日">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="职业" prop="occupation">
            <el-select v-model="form.occupation" placeholder="请选择职业">
              <el-option v-for="dict in dictDataMap['profession_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="婚姻" prop="marriage">
            <el-select v-model="form.marriage" placeholder="请选择婚姻">
              <el-option v-for="dict in dictDataMap['marriage_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="籍贯" prop="nativePlace">
            <level-address :value="form.nativePlaceCode" style="width: 40%;"
                           @handleChange="handleChangeNativePlaceCode"/>
            <el-input v-model="form.nativePlace"  placeholder="请输入籍贯" style="width: 60%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="出生地" prop="homePlace">
            <level-address :value="form.homePlaceCode" style="width: 40%;"
                           @handleChange="handleChangeHomePlaceCode"/>
            <el-input v-model="form.homePlace"  placeholder="请输入出生地" style="width: 60%;"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="现住址" prop="address">
            <level-address :value="form.addressCode" style="width: 40%;"
                           @handleChange="handleChangeAddressCode"/>
            <el-input v-model="form.address" auto-complete=""  placeholder="请输入户口地址"
                      style="width: 60%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="户口地址" prop="registAddress">
            <level-address :value="form.registAddressCode" style="width: 40%;"
                           @handleChange="handleChangeRegistAddressCode"/>
            <el-input v-model="form.registAddress" auto-complete=""
                      placeholder="请输入户口地址" style="width: 60%;"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="工作单位" prop="workContract">
            <el-input v-model="form.workContract" placeholder="请输入工作单位"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工作单位电话" prop="workPhone">
            <el-input v-model="form.workPhone" placeholder="请输入工作单位电话"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="邮编" prop="zipCode">
            <el-input v-model="form.zipCode" placeholder="请输入邮编"/>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" placeholder="请输入备注"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left"><span class="divider-title">▶入院信息◀</span></el-divider>
      <el-row class="extra-margin">
        <el-col :span="6">
          <el-form-item label="入院科室" prop="deptAdmissionTo">
            <dept-list
              v-model="form.deptAdmissionTo"
              :clinic-vs-visit-str="'1,2'"
              :dept-id="form.deptAdmissionTo"
              :org-id="userInfo.orgId"
              :placeholder="'请选择入院科室'"
              style="width: 100%"
              @deptChange="deptChange"
              :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入院病区" prop="wardAdmissionTo">
            <dept-vs-bed-list
              v-model="form.wardAdmissionToName"
              :clinical-sign-str="'3'"
              :dept-id="form.wardAdmissionTo"
              :org-id="userInfo.orgId"
              :placeholder="'请选择入院病区'"
              style="width: 100%"
              @deptChange="wordChange"
              :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入院途径" prop="channel">
            <el-select v-model="form.channel" placeholder="请选择入院途径">
              <el-option v-for="dict in dictDataMap['patient_class_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="入院情况" prop="hospitalSituation">
            <el-select v-model="form.hospitalSituation" placeholder="请选择入院情况">
              <el-option v-for="dict in dictDataMap['admission_situation_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="门诊诊断" prop="diagnosis">
            <el-input v-model="form.clinicDiagnosis"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="隔离情况">
            <el-select v-model="form.quarantine"  placeholder="请选择隔离情况">
              <el-option v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="住院次数">
            {{ form.hospitalizationNumber ? form.hospitalizationNumber + "次" : "暂无" }}
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left"><span class="divider-title">▶医保信息◀</span></el-divider>
      <el-row class="extra-margin">
        <el-col :span="6">
          <el-form-item label="费别" prop="chargeType">
            <el-select v-model="form.chargeType" placeholder="请选择费别"
                       @change="chargeTypeChange">
              <el-option v-for="dict in dictDataMap['medical_insurance_type']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="业务类型:" prop="ybSerialType">
            <el-select v-model="form.ybSerialType" placeholder="业务类型">
              <el-option v-for="dict in dictDataMap['outp_settlement_business_type_dict']"
                         :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="参保类型" prop="insuranceType">
            <el-select v-model="form.insuranceType" placeholder="请选择参保类型">
              <el-option v-for="dict in dictDataMap['insurance_type']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="医保个人编号" prop="yiBaoCardCode">
            {{ form.yiBaoCardCode ? form.yiBaoCardCode : "暂无" }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="医保登记号" prop="yiBaoNumber">
            {{ form.yiBaoNumber ? form.yiBaoNumber : "暂无" }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="计划生育手术类别" prop="birctrlType">
            <el-input v-model="form.birctrlType" placeholder="请输入计划生育手术类别"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="计划生育手术时间" prop="birctrlMatnDate">
            <el-date-picker v-model="form.birctrlMatnDate" type="date" value-format="YYYY-MM-DD"
                            placeholder="请选择计划生育手术时间"/>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="计划生育服务证号" prop="fpscNo">
            <el-input v-model="form.fpscNo" placeholder="请输入计划生育服务证号"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="病种编码" prop="yiBaoDiagnosis">
            <el-input v-model="form.yiBaoDiagnosis" placeholder="请输入病种编码"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="病种名称" prop="yiBaoDiagnosisName">
            <el-input v-model="form.yiBaoDiagnosisName" placeholder="请输入病种名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手术操作代码" prop="yiBaoOperationCode">
            <el-input v-model="form.yiBaoOperationCode" placeholder="请输入手术操作代码"/>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="手术操作名称" prop="yi_bao_operation_name">
            <el-input v-model="form.yiBaoOperationName" placeholder="请输入手术操作名称"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="生育类别" prop="matnType">
            <el-input v-model="form.matnType" placeholder="请输入生育类别"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="孕周数" prop="gesoVal">
            <el-input v-model="form.gesoVal" placeholder="请输入孕周数" type="number"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="胎次" prop="fetts">
            <el-input v-model="form.fetts" placeholder="请输入胎次" type="number"/>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="胎儿数" prop="fetusCnt">
            <el-input v-model="form.fetusCnt" placeholder="请输入胎儿数" type="number"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="是否外伤" prop="isTrauma">
            <el-select v-model="form.isTrauma"  placeholder="请选择是否外伤">
              <el-option v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="本地状态" prop="localFlag">
            <el-select v-model="form.localFlag"  placeholder="本地状态">
              <el-option v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否晚育" prop="latechbFlag">
            <el-select v-model="form.latechbFlag"  placeholder="请选择是否晚育">
              <el-option v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="是否早产" prop="pretFlag">
            <el-select v-model="form.pretFlag"  placeholder="请选择是否早产">
              <el-option v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>


      <el-divider content-position="left"><span class="divider-title">▶紧急联系人◀</span></el-divider>
      <el-row class="extra-margin">
        <el-col :span="6">
          <el-form-item label="联系人姓名" prop="contacts">
            <el-input v-model="form.contacts" placeholder="请输入联系人"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系人电话" prop="contactsPhone">
            <el-input v-model="form.contactsPhone" placeholder="请输入联系人电话"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系人关系" prop="contactsRelation">
            <el-select v-model="form.contactsRelation" placeholder="请选择联系人关系">
              <el-option v-for="dict in dictDataMap['relationship_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="联系人身份证号" prop="contactsIdNo">
            <el-input v-model="form.contactsIdNo" placeholder="请输入联系人身份证号"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系人地址" prop="contactsAddress">
            <level-address :value="form.contactsAddressCode" style="width: 40%;"
                           @handleChange="handleChangeContactsAddressCode"/>
            <el-input v-model="form.contactsAddress" placeholder="请输入联系人地址" style="width: 60%;"/>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
  </div>
  <template v-if="isShowDrawer">
    <div class="in-common" @click="drawerClick">待入院患者</div>
    <el-drawer v-model="drawer" :direction="direction" size="46%" title="待入院患者" @close="handleClose">
      <hospitalization-notice-table ref="hospitalizationNoticeTableRef" :column-is-show="false"
                                    @row-click="rowClick"/>
    </el-drawer>
  </template>

<!--   读卡弹窗-->
  <ReadCardVue
      ref="readCardRef"
      :card-data="cardData"
  />
</template>

<script lang="ts">
export default {
  name: "PatVisitIndexForm"
}
</script>
<script setup lang="ts">
import {
  selectPagePatVisitIndex, addPatVisitIndex, updatePatVisitIndex, delPatVisitIndex, listPatVisitIndex
} from "@/api/hospitalization/patVisitIndex";
import hospitalizationNoticeTable from '@/views/hospitalization/hospitalizationNotice/table.vue';
import ReadCardVue from "@/views/msip/readCard/readCard.vue";
import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user";
import {idNo, phone} from "@/utils/myRules";
import readCardts, {MedicalCardData, ReadCardParams} from "@/api/msip/readCard";
import {selectConfigByCache} from "@/api/system/orgConfig.ts";
import {ElMessage} from "element-plus";
import {mdtrtInfo, mdtrtChange, mdtrtUndo} from "@/api/msip/ipSetl.ts";

const useUserStore = useUserStoreHook();
const readCardRef = ref();
const apiDictType = ref(); //地区字典
const { idAuth } = readCardts();
const cardData = ref<MedicalCardData>();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('profession_dict', 'nationality_dict', 'medical_insurance_type', 'sys_yes_no',
    'sys_user_sex', 'nation_dict', 'marriage_dict', 'admission_situation_dict', 'entry_and_exit_hospital_status', 'medical_read_card_type'
    , 'patient_class_dict', 'relationship_dict', 'insurance_type','outp_settlement_business_type_dict', 'medical_insurance_type'))

const {proxy} = getCurrentInstance() as any;
const hospitalizationNoticeTableRef = ref()
const formRef = ref();
const drawer = ref(false)
const direction = ('rtl')
const open = ref(false);
const isMedical = ref(false);
const mdtrt_cert_type = ref();//就诊凭证类型
const mdtrt_cert_no = ref("");//就诊凭证编号
const insuplc_admdvs = ref("");//参保地区划
const emits = defineEmits(["submitOk"])

const handleClose = (done: () => void) => {
  drawer.value = false
}

/**
 * 通过orgId key获取ApiDictType
 */
function selectApiDictType() {
  debugger
  selectConfigByCache(userInfo.orgId, "api_dict_type").then((res => {
    apiDictType.value = res.data.configValue
  }));
}

const props = defineProps({
  isShowDrawer: {
    type: Boolean,
    default: true
  }
})

const form = ref<any>({
  clinicId: "",
  name: "",
  inputCode: "",
  sex: "",
  age: "",
  ageMonth: 0,
  ageDay: 0,
  ageHours: 0,
  ageMinutes: 0,
  nation: "",
  nationality: "",
  marriage: "",
  occupation: "",
  bedNum: "",
  birthdayDate: "",
  nativePlace: "",
  nativePlaceCode: "",
  zipCode: "",
  homeplace: "",
  homeplaceCode: "",
  address: "",
  addressCode: "",
  identity: "",
  inFlag: "",
  idNo: "",
  phone: "",
  contacts: "",
  contactsRelation: "",
  contactsNation: "",
  contactsIdentity: "",
  contactsAddressCode: "",
  contactsAddress: "",
  contactsPhone: "",
  unitInContract: "",
  chargeType: "",
  deptAdmissionTo: "",
  wardAdmissionTo: "",
  admissionTime: "",
  acceptingMoney: "",
  attackdate: "",
  hospitalSituation: "",
  quarantine: "",
  diagnosis: "",
  diagnosisDesc: "",
  attention: "",
  orgId: "",
  medicalReadCardType: "3",
  isTrauma: "N"
})
const rules = ref({
  name: [
    {
      required: true, message: "患者姓名不能为空", trigger: "blur"
    }
  ],
  sex: [
    {
      required: true, message: "性别不能为空", trigger: "change"
    }
  ],
  nativePlace: [
    {
      required: true, message: "籍贯不能为空", trigger: "change"
    }
  ],
  address: [
    {
      required: true, message: "现住址不能为空", trigger: "change"
    }
  ],

  paymentAdvice: [
    {
      required: true, message: "建议预交金不能为空", trigger: "blur"
    }
  ],
  admissionTime: [
    {
      required: true, message: "入院时间不能为空", trigger: "change"
    }
  ],
  idNo: [{required: true, validator: idNo, trigger: "blur"}],
  phone: [{required: true, message: "电话不能为空", trigger: "blur"}],
  contactsPhone: [{required: true, message: "电话不能为空", trigger: "blur"}],
  contacts: [
    {
      required: true, message: "联系人不能为空", trigger: "blur"
    }
  ],
  deptAdmissionTo: [
    {
      required: true, message: "入院科室不能为空", trigger: "change"
    }
  ],
  wardAdmissionTo: [
    {
      required: true, message: "入院病区不能为空", trigger: "change"
    }
  ],
})

onMounted(() => {
  //获取地区自字典
  selectApiDictType();
});

/** 查询住院通知单列表 */
function getList() {
  // selectPagePatVisitIndex(queryParams.value).then((response: any) => {
  //     HospitalizationNoticeList.value = response.rows;
  //     total.value = response.total;
  // });
}

// 取消按钮
function cancel() {
  open.value = false;
}


/** 重置按钮操作 */
function resetQuery() {
  form.value = {
    clinicDiagnosis: "",
    visitIndexId: "",
    visitId: "",
    newbornFlag: "0",
    name: "",
    inputCode: "",
    height: "",
    weight: 0,
    sex: "",
    marriage: "",
    occupation: "",
    age: 0,
    ageMonth: 0,
    ageDay: 0,
    ageHours: 0,
    ageMinutes: 0,
    nation: "",
    nationality: "",
    ybSerialType : "",
    yiBaoDiagnosisName: "",
    yiBaoDiagnosis: "",
    yiBaoOperationCode: "",
    yiBaoOperationName: "",
    yiBaoCardCode: "",
    yiBaoNumber: "",
    birthdayDate: "",
    nativePlace: "",
    nativePlaceCode: "",
    zipCode: "",
    homePlaceCode: "",
    homePlace: "",
    addressCode: "",
    address: "",
    identity: "",
    idNo: "",
    phone: "",
    contacts: "",
    contactsAddress: "",
    contactsAddressCode: "",
    contactsPhone: "",
    contactsRelation: "",
    unitInContractId: "",
    unitInContract: "",
    workContract: "",
    affiliatingArea: "",
    insuranceType: "",
    isCard: "",
    chargeType: "",
    externalCause: "",
    autopsyFlag: "",
    practiceDoctor: "",
    engageDoctor: "",
    isDrugAllerge: "",
    drugAllergy: "",
    orgId: "",
    delFlag: "",
    createBy: "",
    createTime: "",
    updateBy: "",
    updateTime: "",
    remarks: "",
    medicalReadCardType: "3",
    rh: "",
    abo: "",
    pathologicalDiagCode: "",
    pathologicalNo: "",
    pathologicalDiag: "",
    registZipCode: "",
    registAddress: "",
    registAddressCode: "",
    workCode: "",
    workPhone: "",
    externalCauseCode: "",
    paymentAdvice: 0,
    residenceNo: "",
    medicalPayWay: "",
    brainDamageTimeBeforeDay: "",
    brainDamageTimeBeforeHour: "",
    brainDamageTimeBeforeMinute: "",
    brainDamageTimeAfterDay: "",
    brainDamageTimeAfterHour: "",
    brainDamageTimeAfterMinute: "",
    comeAgainIf: "0",
    comeAgainPurpose: "",
    persType: "",
    centerId: "",
    eduLevel: "",
    matnType: "",
    latechbFlag: "",
    pretFlag: "",
    birctrlMatnDate: "",
    fpscNo: "",
    birctrlType: "",
    gesoVal: "",
    fetts: "",
    fetusCnt: "",
    localFlag: ""
  }
}

// 身份证获取患者性别、出生年月日、年龄
function certificateNoBlur() {
  const idNo = form.value.idNo
  // 获取性别
  const sex = proxy.$certificateNoInSex(idNo)
  form.value.sex = sex
  // 获取出生年月日
  const birthday = proxy.$certificateNoInBirthday(idNo)
  form.value.birthdayDate = birthday
  // 获取年龄 返回年月日小时对象
  const ageObj = proxy.$certificateNoInAge(birthday)
  if (ageObj) {
    form.value.age = ageObj.yStr
    form.value.ageMonth = ageObj.mStr
    form.value.ageDay = ageObj.dStr
    form.value.ageHours = ageObj.hStr
  }
}

function rowClick(row) {
  form.value = row
  listPatVisitIndex({patientId: row.patientId}).then((res: resType) => {
    if (res.data) {
      form.value.hospitalizationNumber = res.data.length
    } else {
      form.value.hospitalizationNumber = 0
    }
  })
  drawer.value = false
}

// /** 修改按钮操作 */
// function handleUpdate(row) {
//     open.value = true;
//     reset();
//     const _noticeId = row.noticeId || ids.value
//     getHospitalizationNotice(_noticeId).then((response: any) => {
//         form.value = response.data;
//         title.value = "修改住院通知单";
//     });
// }

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      if (form.value.visitId != null) {
        updatePatVisitIndex(form.value).then(() => {
          ElMessage.success("登记成功");
          open.value = false;
          resetQuery()
          emits("submitOk")
        }).finally(() => {
        });
      } else {
        addPatVisitIndex(form.value).then(() => {
          ElMessage.success("登记成功");
          open.value = false;
          resetQuery()
        }).finally(() => {
        });
      }
    }
  });
}

/**费别点击事件 */
function chargeTypeChange(value: string) {
  if (value === "1") {
    form.value.ybSerialType = "4";
  } else {
    form.value.ybSerialType = "11";
  }
}

/** 读卡 */
async function handleReadCard(businesstype) {
  if (!form.value.medicalReadCardType) {
    return ElMessage.error("请选择读卡类型！");
  }
  mdtrt_cert_type.value = '0' + form.value.medicalReadCardType;
  mdtrt_cert_no.value = form.value.idNo;
  try {
    const params: ReadCardParams = {
      mdtrt_cert_type: mdtrt_cert_type.value, //就诊凭证类型: 01=医保电子凭证 02=居民身份证 03=社会保障卡 04=终端扫码 05=终端扫脸
      cardtype: "0",                                  //卡片类型: 0=实体卡 1=电子社保卡 mdtrt_cert_type 为“03”时必填
      businesstype: businesstype,                     //用码业务类型: 01301=结算 mdtrt_cert_type 为“01”时必填
      operatorid: userInfo.userId,                    // 收款员编号 mdtrt_cert_type 为“01”时必填
      operatorname: userInfo.userName,                // 收款员姓名 mdtrt_cert_type 为“01”时必填
      officeid: "",                                   // 医保科室编号 mdtrt_cert_type 为“01”时必填
      officename: "",                                 // 科室名称 mdtrt_cert_type 为“01”时必填
      org_id: userInfo.orgId,                         // 机构ID
      name: form.value.name,
      idNo: form.value.idNo,
      his_user_id: userInfo.userId                    // 用户ID
    };
    debugger
    await idAuth(params, apiDictType.value,mdtrt_cert_no).then(res => {
      debugger
      cardData.value = res;
      nextTick(() => {
        readCardRef.value.show(); // 确保数据赋值后再显示弹窗
      });
    });
  } catch (err) {
    ElMessage.error('读卡错误：'+ err);
  }
  form.value.yiBaoCardCode = cardData.value?.baseinfo.psn_no;
  // 使用for循环为参保类型赋值
  cardData.value?.insuinfo.forEach((item, index) => {
    if (item.psn_insu_stas == 1) {
      form.value.insuranceType = item.insutype;
      insuplc_admdvs.value = item.insuplc_admdvs;
    }
  });
}

/** 医保登记 */
function mdtrt() {
  if (!cardData.value) {
    return ElMessage.error('请读卡进行身份认证！');
  }
  if (!form.value.ybSerialType) {
    return ElMessage.error('请选择业务类型！');
  }
  const param = {
    mdtrt_cert_type: mdtrt_cert_type.value,// 就诊凭证类型 字符型 3 Y Y
    mdtrt_cert_no: mdtrt_cert_no.value,// 就诊凭证编号 字符型 50 Y 就诊凭证类型为“01”时填写电子凭证令牌，为“02”时填写身份证号，为“03”时填写社会保障卡卡号
    psn_no: form.value.yiBaoCardCode,// 人员编号 字符型 20 Y Y
    insutype: form.value.insuranceType,// 险种类型 20 Y Y Y
    med_type: form.value.ybSerialType,// 医疗类别
    dise_codg: form.value.yiBaoDiagnosis,// 病种编码
    dise_name: form.value.yiBaoDiagnosisName, // 病种名称
    oprn_oprt_code: form.value.yiBaoOperationCode, // 手术操作代码
    oprn_oprt_name: form.value.yiBaoOperationName, // 手术操作名称
    fpsc_no: form.value.fpscNo, // 计划生育服务证号
    matn_type: form.value.matnType, // 生育类别
    birctrl_type: form.value.birctrlType, // 计划生育手术类别
    latechb_flag: form.value.latechbFlag, // 晚育标志
    geso_val: form.value.gesoVal, // 孕周数
    fetts: form.value.fetts, // 胎次
    fetus_cnt: form.value.fetusCnt, // 胎儿数
    pret_flag: form.value.pretFlag, // 早产标志
    birctrl_matn_date: form.value.birctrlMatnDate, // 计划生育手术或生育日期
    certno: form.value.idNo,
    psn_name: form.value.name,
    insuplc_admdvs: insuplc_admdvs.value,//参保地区编码
    org_id: userInfo.orgId,//机构ID
    his_user_id: userInfo.userId,//用户id
    his_mdtrt_id: form.value.visitId,//就诊id
    psn_info: cardData.value,//人员信息
  }
  mdtrtInfo(param).then((res: resType) => {
    if (res && res.code === 200) {
      ElMessage.success("医保登记成功！");
      form.value.yiBaoNumber  = res.data.output.result.mdtrt_id
    }else{
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    return ElMessage.error(err)
  });
}

/** 医保信息变更 */
function mdtrtUpdate() {
  if (!form.value.ybSerialType) {
    return ElMessage.error('请选择业务类型！');
  }
  const param = {
    mdtrt_cert_type: '0' + form.value.medicalReadCardType,// 就诊凭证类型 字符型 3 Y Y
    psn_no: form.value.yiBaoCardCode,// 人员编号 字符型 20 Y Y
    mdtrt_id: form.value.yiBaoNumber,// 就诊ID
    insutype: form.value.insuranceType,// 险种类型 20 Y Y Y
    med_type: form.value.ybSerialType,// 医疗类别
    dise_codg: form.value.yiBaoDiagnosis,// 病种编码
    dise_name: form.value.yiBaoDiagnosisName, // 病种名称
    oprn_oprt_code: form.value.yiBaoOperationCode, // 手术操作代码
    oprn_oprt_name: form.value.yiBaoOperationName, // 手术操作名称
    fpsc_no: form.value.fpscNo, // 计划生育服务证号
    matn_type: form.value.matnType, // 生育类别
    birctrl_type: form.value.birctrlType, // 计划生育手术类别
    latechb_flag: form.value.latechbFlag, // 晚育标志
    geso_val: form.value.gesoVal, // 孕周数
    fetts: form.value.fetts, // 胎次
    fetus_cnt: form.value.fetusCnt, // 胎儿数
    pret_flag: form.value.pretFlag, // 早产标志
    birctrl_matn_date: form.value.birctrlMatnDate, // 计划生育手术或生育日期
    certno: form.value.idNo,
    psn_name: form.value.name,
    insuplc_admdvs: insuplc_admdvs.value,//参保地区编码
    org_id: userInfo.orgId,//机构ID
    his_user_id: userInfo.userId,//用户id
    his_mdtrt_id: form.value.visitId,//就诊id
  }
  mdtrtChange(param).then((res: resType) => {
    if (res && res.code === 200) {
      ElMessage.success("医保信息变更成功！");
      form.value.yiBaoNumber  = res.data.output.result.mdtrt_id
    }else{
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    return ElMessage.error(err)
  });
}

/** 医保登记撤销 */
function mdtrtCancel() {
  if (form.value.chargeType != "1") {
    return ElMessage.error('请将费别选择为自费再进行操作！');
  }
  const param = {
    psn_no: form.value.yiBaoCardCode,// 人员编号 字符型 20 Y Y
    mdtrt_id: form.value.yiBaoNumber,// 就诊ID
    org_id: userInfo.orgId,//机构ID
    his_user_id: userInfo.userId,//用户id
    his_mdtrt_id: form.value.visitId,//就诊id
  }
  mdtrtUndo(param).then((res: resType) => {
    if (res && res.code === 200) {
      ElMessage.success("入院撤销成功！");
    }else{
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    return ElMessage.error(err)
  });
}

function wordChange(obj) {
  form.value.wardAdmissionTo = obj.wardCode
  form.value.deptAdmissionToName = obj.wardCodeName
}

function deptChange(obj) {
  form.value.deptAdmissionTo = obj.deptId
}

function handleChangeContactsAddressCode(obj: any) {
  if (obj) {
    form.value.contactsAddressCode = obj['townlet'].value
    form.value.contactsAddress = initAddrStr(obj)
  }
}

function handleChangeHomePlaceCode(obj: any) {
  if (obj) {
    form.value.homePlaceCode = obj['townlet'].value
    form.value.homePlace = initAddrStr(obj)
  }
}

function handleChangeNativePlaceCode(obj: any) {
  if (obj) {
    form.value.nativePlaceCode = obj['townlet'].value
    form.value.nativePlace = initAddrStr(obj)
  }
}

function handleChangeRegistAddressCode(obj: any) {
  if (obj) {
    form.value.registAddressCode = obj['townlet'].value
    form.value.registAddress = initAddrStr(obj)
  }
}

function handleChangeAddressCode(obj: any) {
  if (obj) {
    form.value.addressCode = obj['townlet'].value
    form.value.address = initAddrStr(obj)

  }
}

function initAddrStr(obj: any) {
  return obj['economize'].label + obj['city'].label + obj['county'].label + obj['townlet'].label + form.value.address
}

function drawerClick() {
  drawer.value = true
  nextTick(() => {
    hospitalizationNoticeTableRef.value.getList()
  })
}

/**
 * 重新登记
 */
function anewRegistrationFun (row:any) {
  form.value = row;
  form.value.medicalReadCardType = "3"; // 读卡类型默认读卡
  isMedical.value = true;
  listPatVisitIndex({patientId: row.patientId}).then((res: resType) => {
    if (res.data) {
      form.value.hospitalizationNumber = res.data.length
    } else {
      form.value.hospitalizationNumber = 0
    }
  })
}

getList();

defineExpose({
  anewRegistrationFun,
  resetQuery
})
</script>

<style scoped>
:deep(.age .el-input__inner) {
  width: 35px;
}
/* 增加表单项之间的垂直间距 */
.divider-title {
  color: rgb(6, 138, 194);
  font-weight: bold;
  font-size: 14px;
}
.extra-margin {
  margin-top: 30px; /* 根据需要调整具体的值 */
}


</style>
